package util;


import javax.sql.DataSource;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 加载好的Spring BeanFactory对象
 * 
 * @author baiyh
 * @date 2011-1-22
 */
public class BeanFactoryUtil {

	private static BeanFactory beanFactory = null;

	public static BeanFactory getBeanFactory() {
		//获取beanfacture,如果为null,则从classpath重新加载
		if (beanFactory == null) {
			synchronized (BeanFactoryUtil.class) {
				if (beanFactory == null) {
					beanFactory = new ClassPathXmlApplicationContext(
							"classpath:applicationContext.xml");
				}
			}
		}
		return beanFactory;
	}

	/**
	 * 根据beanName获取注册的对象
	 * 
	 * @param beanName
	 * @return
	 */
	public static Object getBean(String beanName) {
		return getBeanFactory().getBean(beanName);
	}

	/**
	 * 设置BeanFactory,用于启动加载时使用,其他地方不能调用此方法
	 * @param factory
	 */
	public static void setBeanFactory(BeanFactory factory) {
		BeanFactoryUtil.beanFactory = factory;
	}
	

	public static void main(String[] args) {
		DataSource dataSource = (DataSource) BeanFactoryUtil.getBean("dataSource");
		System.out.println(dataSource);
	}

}
